
/**
 * Copyright (2024, ) Institute of Software, Chinese Academy of Sciences
 * author: wuheng@iscas.ac.cn
 * since:  0.1.0
 **/
use diesel::{PgConnection, RunQueryDsl};
use diesel::SqliteConnection;
use serde_json::Value;
use diesel::result::Error;
use diesel::sql_query;
use diesel::sql_types::Text;

pub fn update_sqlite3_object(conn: &mut SqliteConnection, table: &str, data: Value) -> Result<bool, Error> {

    use diesel::sql_query;

    let name_value = data["name"].as_str().ok_or(Error::NotFound)?;
    let namespace_value = data["namespace"].as_str().ok_or(Error::NotFound)?;
    let apigroup_value = data["apigroup"].as_str().ok_or(Error::NotFound)?;
    let data_value = data["data"].to_string();

    let query = sql_query(generate_update_sqlite3_object_sql(table))
        .bind::<Text, _>(&data_value)
        .bind::<Text, _>(name_value)
        .bind::<Text, _>(namespace_value)
        .bind::<Text, _>(apigroup_value);


    match query.execute(conn) {
        Ok(_) => Ok(true),
        Err(e) => Err(e),
    }
}

pub fn update_postgres_object(conn: &mut PgConnection, table: &str, data: Value) -> Result<bool, Error> {

    use diesel::sql_query;

    let name_value = data["name"].as_str().ok_or(Error::NotFound)?;
    let namespace_value = data["namespace"].as_str().ok_or(Error::NotFound)?;
    let apigroup_value = data["apigroup"].as_str().ok_or(Error::NotFound)?;
    let data_value = data["data"].to_string();

    let query = sql_query(generate_update_postgres_object_sql(table))
        .bind::<Text, _>(name_value)
        .bind::<Text, _>(namespace_value)
        .bind::<Text, _>(apigroup_value)
        .bind::<Text, _>(&data_value);

    match query.execute(conn) {
        Ok(_) => Ok(true),
        Err(e) => Err(e),
    }
}

fn generate_update_postgres_object_sql(table_name: &str) -> String {
    format!("UPDATE {} SET data = $4::json, updated = NOW()
         WHERE name = $1 AND namespace = $2 AND apigroup = $3;",
            table_name
    )
}

fn generate_update_sqlite3_object_sql(table_name: &str) -> String {
    format!("UPDATE {} SET data = ?, updated = DATETIME('now')
         WHERE name = ?  AND namespace = ? AND apigroup = ?;",
            table_name
    )
}